package com.hrzyit.whistle.cases.ui.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.map.*
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.search.core.PoiInfo
import com.baidu.mapapi.search.core.SearchResult
import com.baidu.mapapi.search.geocode.*
import com.hrzyit.base.ext.onClick
import com.hrzyit.base.ui.activity.BaseActivity
import com.hrzyit.base.ui.adapter.BaseRecyclerViewAdapter
import com.hrzyit.provider.common.ProviderConstant
import com.hrzyit.whistle.cases.R
import com.hrzyit.whistle.cases.ui.adapter.LocationMapListAdapter
import com.hrzyit.whistle.cases.ui.fragment.BaiDuMapFragment
import kotlinx.android.synthetic.main.activity_location_map.*
import org.jetbrains.anko.toast

/**
 * 地图界面 Activity
 */
@Deprecated(
    "废弃使用 BaiDuMapFragment替代",
    ReplaceWith("BaiDuMapFragment", "com.hrzyit.whistle.cases.ui.fragment.BaiDuMapFragment")
)
class LocationMapActivity : BaseActivity() {

    companion object {
        const val TAG = "LocationMapActivity"
    }

    // -- 百度地图相关配置
    private lateinit var mBaiDuMap: BaiduMap

    private lateinit var mLocationClient: LocationClient

    private lateinit var casePointIcon: BitmapDescriptor

    private lateinit var locationMapListAdapter: LocationMapListAdapter

    private var latitudePos: String? = null
    private var longitudePos: String? = null
    private var caseAddress: String? = null

    // 页面加载第一定位
    private var isFirstLoc: Boolean = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_location_map)

        initView()

        // 初始化地图标注图片资源
        casePointIcon = BitmapDescriptorFactory.fromResource(
            R.drawable.login_icon_location
        )

        initLocation(this)


        // 设置已选择案件地点的标注
        val isLatLong = latitudePos != null && longitudePos != null
        when (isLatLong) {
            true -> {
                val initPointOptions = MarkerOptions()
                initPointOptions.icon(casePointIcon)
                val initLatLang = LatLng(39.925377, 116.348844)
                initPointOptions.position(initLatLang)
                mBaiDuMap.addOverlay(initPointOptions)
                // 地图移到中间
                mBaiDuMap.setMapStatus(
                    MapStatusUpdateFactory.newLatLng(initLatLang)
                )
            }
        }
    }

    /**
     * 初始化定位
     */
    private fun initLocation(context: Context) {
        // 初始化地图
        mBaiDuMap = mLocationMapView.map
        mBaiDuMap.clear()

        // 定位初始化
        mLocationClient = LocationClient(context)

        // 开启定位我的位置
        mBaiDuMap.isMyLocationEnabled = true

        // 控制缩放级别
        val mapStatus = MapStatus.Builder()
        mapStatus.zoom(17.0f)
        mBaiDuMap.setMapStatus(
            MapStatusUpdateFactory.newMapStatus(mapStatus.build())
        )

        // 定位显示当前『我』的位置监听器
        // 实现BDAbstractLocationListener接口
        // Android定位SDK自V7.2版本起，对外提供了Abstract类型的监听接口BDAbstractLocationListener，
        // 用于实现定位监听。原有BDLocationListener暂时保留，推荐开发者升级到Abstract类型的新监听接口使用，该接口会异步获取定位结果，
        val locationListener = (object : BDAbstractLocationListener() {
            override fun onReceiveLocation(location: BDLocation?) {
                // mLocationMapView 销毁后不在处理新接收的位置
                if (location == null || mLocationMapView == null) {
                    return
                }

                val locData: MyLocationData = MyLocationData.Builder()
                    .accuracy(location.radius)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(location.direction)
                    .latitude(location.latitude)
                    .longitude(location.longitude).build()

                mBaiDuMap.setMyLocationData(locData)

                // 第一定位到我的位置
                when (isFirstLoc) {
                    true -> {
                        val lagLng = LatLng(location.latitude, location.longitude)
                        val builder = MapStatus.Builder().target(lagLng).zoom(18.0f)
                        mBaiDuMap.animateMapStatus(
                            MapStatusUpdateFactory.newMapStatus(
                                builder.build()
                            )
                        )
                        isFirstLoc = !isFirstLoc
                    }
                }
            }
        })

        // 初始化百度地图 Option
        initLocationOption()


        // 注册 LocationListener 监听器
        mLocationClient.registerLocationListener(locationListener)

        // 开启地图定位图层
        mLocationClient.start()


        // 点击地图事件
        mBaiDuMap.setOnMapClickListener(object : BaiduMap.OnMapClickListener {
            override fun onMapClick(point: LatLng?) {
                transLatLngToAddress(point!!)
            }

            override fun onMapPoiClick(mapPoi: MapPoi?): Boolean {
                return false
            }

        })

    }

    /**
     * 初始化百度地图 Option
     */
    private fun initLocationOption() {
        // 通过LocationClientOption设置LocationClient相关参数
        val option = LocationClientOption()
        // 打开gps
        option.openGps = true
        // 设置坐标类型
        option.coorType = "bd09ll"

        option.scanSpan = 3000

        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.locationMode = LocationClientOption.LocationMode.Hight_Accuracy

        // 获取详细地址
        option.setIsNeedAddress(true)

        // 可选，是否需要周边POI信息，默认为不需要，即参数为false;如果开发者需要获得周边POI信息，此处必须为true
        option.setIsNeedLocationPoiList(true)

        // 设置 locationClientOption
        mLocationClient.locOption = option
    }

    /**
     * 初始化视图 View init
     */
    private fun initView() {

        // 注册导航头按钮事件
        mLocationMapHeaderBar.getRightView().onClick {
            //            toast("$latitudePos,$longitudePos,$caseAddress")

            val intent = Intent()
            intent.putExtra("latitude", latitudePos)
            intent.putExtra("longitude", longitudePos)
            intent.putExtra("caseAddress", caseAddress)

            setResult(ProviderConstant.RESULT_CODE_ACTIVITY, intent)

            finish()
        }

        // 初始化案件地址选择信息
        val layoutManager = LinearLayoutManager(this) // 线性布局
        mLocationMapListRv.layoutManager = layoutManager

        locationMapListAdapter = LocationMapListAdapter(this)

        mLocationMapListRv.adapter = locationMapListAdapter

        locationMapListAdapter.setOnItemClickListener(object : BaseRecyclerViewAdapter.OnItemClickListener<PoiInfo> {

            override fun onItemClick(view: View, item: PoiInfo?, position: Int) {
//                when (view.id) {
//                    R.id.mLocationAddressTv -> {
//                    }
//                }
            }
        })
    }

    /**
     * 经纬度转地址
     * @param latLong
     */
    private fun transLatLngToAddress(latLong: LatLng) {
//        // 初始化搜索模块，注册事件监听
        val mSearch = GeoCoder.newInstance()
        // 反Geo搜索
        mSearch.setOnGetGeoCodeResultListener(object : OnGetGeoCoderResultListener {
            override fun onGetReverseGeoCodeResult(result: ReverseGeoCodeResult?) {
                Log.e("onGetReverseGeo->", "${result?.location}")
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    toast("未获取到地址信息")
                } else {
                    //构建MarkerOption，用于在地图上添加Marker
                    mBaiDuMap.clear()
                    // 地图移到中间
                    mBaiDuMap.setMapStatus(MapStatusUpdateFactory.newLatLng(result.location))

                    val addressOptions = MarkerOptions()
                    addressOptions.position(result.location)
                    addressOptions.icon(casePointIcon)
                    mBaiDuMap.addOverlay(addressOptions)
                    Log.e("address", result.address)

                    // 设置案件地址定位信息
                    latitudePos = "${result.location.latitude}"
                    longitudePos = "${result.location.longitude}"
                    caseAddress = result.address

                    // 获取定位地点周边地址信息并显示在 RecycleView
                    val list = result.poiList
                    locationMapListAdapter.dataList = list
                    locationMapListAdapter.notifyDataSetChanged()

                    // 在地图上添加Marker，并显示
                    mBaiDuMap.addOverlay(addressOptions)
                }
            }

            override fun onGetGeoCodeResult(result: GeoCodeResult?) {
            }
        })
        mSearch.reverseGeoCode(ReverseGeoCodeOption().location(latLong))
    }

    override fun onResume() {
        Log.v(TAG, "onResume-->")
        mLocationMapView.onResume()
        super.onResume()
    }

    override fun onPause() {
        Log.v(TAG, "onPause-->")
        mLocationMapView.onPause()
        super.onPause()
    }

    override fun onDestroy() {
        Log.v(TAG, "onDestroy-->")
        super.onDestroy()
    }
}
